﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Globalization;
using System.Threading;
using System.IO;
using DBCSCodePage;
using HtmlAgilityPack;


namespace NGA
{
    public partial class ContentPage : PhoneApplicationPage
    {
        private string uri = App.HTTP_DOMAIN + "thread.php";
        private int curBoardNumber = -7;
        private int curPage = 1;
        private int curViewState = -1;
        private ScrollViewerHandler viewHandler = null;

        public ContentPage()
        {
            InitializeComponent();
            
            uri = App.HTTP_DOMAIN + "thread.php";
            curPage = 1;
            curBoardNumber = -7;
            curViewState = -1;

            DataContext = App.View;
            MainListBox.SelectionChanged += MainListBox_SelectionChanged;

            viewHandler = new ScrollViewerHandler();

            // test
            UpdateBackTile("江湖的骗子", 702938, new Uri("http://pic1.178.com/avatars/00/0a/b9/120_702938.jpg"));
        }

        void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ListBox)sender).SelectedIndex != -1)
            {
                NavigationService.Navigate(new Uri("/ThreadPage.xaml" + "?href=" + ((MainViewModel)DataContext).Items[((ListBox)sender).SelectedIndex].ItemLink, UriKind.Relative));
                ((ListBox)sender).SelectedIndex = -1;
            }
            //throw new NotImplementedException();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string param = "fid=";
            IDictionary<string, string> query = this.NavigationContext.QueryString;
            if (query.ContainsKey("fid"))
            {
                curBoardNumber = Int32.Parse(query["fid"]);
                param += curBoardNumber.ToString();
            }
            if (query.ContainsKey("update"))
            {
                ((MainViewModel)DataContext).Items.Clear();
                HttpHandler contentRequest = new HttpHandler(uri, param, DBCSEncoding.GetDBCSEncoding("gb2312"), PraseHttpContent);
            }
            this.NavigationContext.QueryString.Clear();

            base.OnNavigatedTo(e);
        }

        private bool PraseHttpContent(String result)
        {
            bool ret;
            System.Diagnostics.Debug.WriteLine(result);
            if (result.Contains("大漩涡"))
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    //MessageBox.Show("Content Read SUCCESS");
                    if (curPage == 1)
                    {
                        ((MainViewModel)DataContext).Items.Clear();
                    }
                });

                HtmlDocument html = new HtmlDocument();
                html.LoadHtml(result);

                for (int i = 0; ; i++)
                {
                    try
                    {
                        HtmlNode topicTitleNode = html.GetElementbyId("t_tt" + i.ToString());

                        string replyCount = html.GetElementbyId("t_rc" + i.ToString()).InnerText;
                        string topicTitle = topicTitleNode.InnerText;
                        string topicAuthor = html.GetElementbyId("t_ta" + i.ToString()).InnerText;
                        string postTime = html.GetElementbyId("t_pt" + i.ToString()).InnerText;
                        string replyTime = html.GetElementbyId("t_rt" + i.ToString()).InnerText;
                        string replyer = html.GetElementbyId("t_tr" + i.ToString()).InnerText;
                        string href = string.Empty;

                        if (Int32.Parse(replyCount) == 0)
                        {
                            replyer = string.Empty;
                            replyCount = "无人回复";
                        }
                        else
                        {
                            if (replyer == topicAuthor)
                            {
                                replyer = "楼主";
                            }
                            replyCount += "回复";
                        }

                        foreach (HtmlAttribute attr in topicTitleNode.Attributes)
                        {
                            if (attr.Name == "href")
                            {
                                href = App.HTTP_DOMAIN + attr.Value;
                            }
                        }

                        TimeSpan ts = TimeSpan.FromSeconds(Int32.Parse(postTime));
                        DateTime time = new DateTime(1970, 1, 1).ToLocalTime() + ts;
                        postTime = time.ToString("M/d HH:mm:ss");

                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            ((MainViewModel)DataContext).Items.Add(new ItemViewModel()
                            {
                                ItemTitle = topicTitle,
                                ItemAuthor = topicAuthor,
                                ItemTail = replyer,
                                ItemTail2 = replyCount,
                                ItemLink = href
                            });
                        });
                    }
                    catch (System.Exception ex)
                    {
                        break;
                    }
                }
                ret = true;
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Content Read FAILURE");
                });
                ret = false;
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                loadProgress.Visibility = System.Windows.Visibility.Collapsed;
                viewHandler.ProcessViewer(MainListBox, visualStateGroup_CurrentStateChanged);
            });

            return ret;
        }

        /// <summary>
        /// 状态改变
        /// </summary>
        private void visualStateGroup_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
        {
            string visualState = e.NewState.Name;
            ScrollViewer view = viewHandler.scrollViewer;


            if (visualState == "NotScrolling")
            {
                if (view.ExtentHeight - view.VerticalOffset - view.ViewportHeight <= +0.000001)
                {
                    if (curViewState == 1)
                    {
                        loadProgress.Visibility = System.Windows.Visibility.Visible;
                        curPage++;
                        curViewState = 0;
                        HttpHandler contentRequest = new HttpHandler(
                            uri,
                            "fid=" + curBoardNumber.ToString() + "&" + "page=" + curPage.ToString(),
                            DBCSEncoding.GetDBCSEncoding("gb2312"),
                            PraseHttpContent);                    
                    }
                    else
                    {
                        curViewState = 1;
                    }
                }
                else if (view.VerticalOffset <= 0.000001)
                {
                    if (curViewState == -1)
                    {
                        loadProgress.Visibility = System.Windows.Visibility.Visible;
                        curPage = 1;
                        HttpHandler contentRequest = new HttpHandler(
                            uri,
                            "fid=" + curBoardNumber.ToString() + "&" + "page=" + curPage.ToString(),
                            DBCSEncoding.GetDBCSEncoding("gb2312"),
                            PraseHttpContent);
                    }
                    else
                    {
                        curViewState = -1;
                    }
                }
                else
                {
                    curViewState = 0;
                }
            }
        }

        private void UpdateBackTile(String name, Int32 id, Uri uri)
        {
            // update back tile
            ShellTile tile = ShellTile.ActiveTiles.First();
            if (tile != null)
            {
                StandardTileData tileData = new StandardTileData();

                tileData.BackTitle = id.ToString();
                tileData.BackBackgroundImage = uri;
                tileData.BackContent = name;

                tile.Update(tileData);
            }
        }
    }


}